// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/parser/parser.h>
#include <cantor/transform/stmts/type_stmt.h>
#include <cantor/transform/expr.h>
#include <cantor/transform/exprs/constant_expr.h>
#include <cantor/transform/ddls/enum_element.h>
#include <cantor/transform/clause/type_name_uri.h>
#include <cantor/transform/clause/named_type.h>

namespace cantor::transform {
    void TransTypeStmt::resolve_ast(const cantor::parser::TypeStmt *node) {
        if (!node) {
            status = turbo::data_loss_error("no expr");
            return;
        }
        /// base
        if (node->names.size() < 1) {
            make_missing_required_field("names");
            return;
        }

        type_stmt.mutable_names()->Reserve(node->names.size());
        for (size_t i = 0; i < node->names.size(); ++i) {
            auto name = type_stmt.mutable_names()->Add();
            name->assign(node->names[i].to_string());
        }
        type_stmt.set_type_oid(node->typeOid);
        type_stmt.set_setof(node->setof);
        type_stmt.set_pct_type(node->pct_type);
        type_stmt.mutable_type_mods()->Reserve(node->typmods.size());
        for (size_t i = 0; i < node->typmods.size(); ++i) {
            auto mod = type_stmt.mutable_type_mods()->Add();
            TransConstantExpr cexpr;
            cexpr.resolve_ast(node->typmods[i]);
            status = cexpr.check();
            if (!status.ok()) {
                return;
            }
            *mod = std::move(cexpr.const_expr);
        }
        type_stmt.mutable_array_bounds()->Reserve(node->array_bounds.size());
        for (size_t i = 0; i < node->array_bounds.size(); ++i) {
            auto bound = type_stmt.mutable_array_bounds()->Add();
            TransConstantExpr cexpr;
            cexpr.resolve_ast(node->array_bounds[i]);
            status = cexpr.check();
            if (!status.ok()) {
                return;
            }
            *bound = std::move(cexpr.const_expr);
        }
        type_stmt.set_type(node->typename_type);
        switch (node->typename_type) {
            case pb::ast::TYPE_NAME_GENERIC:
                type_stmt.mutable_generic_arg()->Clear();
                break;
            case pb::ast::TYPE_NAME_NUMERIC: {
                set_numeric(node);
                break;
            }
            case pb::ast::TYPE_NAME_DATETIME: {
                set_datetime(node);
                break;
            }
            case pb::ast::TYPE_NAME_TIMESTAMP: {
                set_timestamp(node);
                break;
            }
            case pb::ast::TYPE_NAME_INTERVAL: {
                set_interval(node);
                break;
            }
            case pb::ast::TYPE_NAME_DURATION: {
                set_duration(node);
                break;
            }
            case pb::ast::TYPE_NAME_JSON: {
                type_stmt.mutable_json_arg()->Clear();
                break;
            }
            case pb::ast::TYPE_NAME_BITMAP: {
                type_stmt.mutable_bitmap_arg()->Clear();
                break;
            }
            case pb::ast::TYPE_NAME_TDIGEST: {
                type_stmt.mutable_tdigest_arg()->Clear();
                break;
            }
            case pb::ast::TYPE_NAME_HLL: {
                type_stmt.mutable_hll_arg()->Clear();
                break;
            }
            case pb::ast::TYPE_NAME_STRING: {
                set_string(node);
                break;
            }
            case pb::ast::TYPE_NAME_MAP: {
                set_map(node);
                break;
            }
            case pb::ast::TYPE_NAME_SET: {
                set_set(node);
                break;
            }
            case pb::ast::TYPE_NAME_TUPLE: {
                set_tuple(node);
                break;
            }
            case pb::ast::TYPE_NAME_UNION: {
                set_union(node);
                break;
            }
            case pb::ast::TYPE_NAME_STRUCT: {
                set_struct(node);
                break;
            }
            case pb::ast::TYPE_NAME_PROTO: {
                set_proto(node);
                break;
            }
            case pb::ast::TYPE_NAME_ENUM: {
                set_enum(node);
                break;
            }
            default:
                status = turbo::invalid_argument_error("unknown type");
        }
        if (!status.ok()) {
            return;
        }
        ///
        set_proto_location(node, type_stmt.mutable_location());
        set_proto_status(type_stmt.mutable_status());
    }

    const turbo::Status &TransTypeStmt::check() {
        if (!status.ok()) {
            return status;
        }
        if (!type_stmt.has_location()) {
            make_missing_required_field("location");
            return status;
        }

        return status;
    }

    void TransTypeStmt::set_numeric(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameNumeric *) node;
        type_stmt.mutable_numeric_arg()->set_numeric_type(ptr->numeric_type);
    }

    void TransTypeStmt::set_datetime(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameDateTime *) node;
        type_stmt.mutable_datatime_arg()->set_precision(ptr->precision);
    }

    void TransTypeStmt::set_timestamp(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameTimestamp *) node;
        type_stmt.mutable_timestamp_arg()->set_precision(ptr->precision);
    }

    void TransTypeStmt::set_interval(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameInterval *) node;
        type_stmt.mutable_interval_arg()->set_precision(ptr->precision);
    }

    void TransTypeStmt::set_duration(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameDuration *) node;
        type_stmt.mutable_duration_arg()->set_precision(ptr->precision);
    }

    void TransTypeStmt::set_string(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameString *) node;
        auto tptr = type_stmt.mutable_string_arg();
        tptr->set_charset(ptr->charset.to_string());
        tptr->set_collate(ptr->collate.to_string());
        tptr->set_is_binary(ptr->is_binary);
    }

    void TransTypeStmt::set_map(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameMap *) node;
        auto tptr = type_stmt.mutable_map_arg();
        if (!ptr->key) {
            make_missing_required_field("key");
            return;
        }
        if (!ptr->value) {
            make_missing_required_field("value");
            return;
        }
        TransTypeStmt k;
        k.resolve_ast(ptr->key);
        status = k.check();
        if (!status.ok()) {
            return;
        }
        *(tptr->mutable_key()) = std::move(k.type_stmt);
        TransTypeStmt v;
        v.resolve_ast(ptr->value);
        status = v.check();
        if (!status.ok()) {
            return;
        }
        *(tptr->mutable_value()) = std::move(v.type_stmt);
    }

    void TransTypeStmt::set_set(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameSet *) node;
        auto tptr = type_stmt.mutable_set_arg();
        if (!ptr->key) {
            make_missing_required_field("key");
            return;
        }
        TransTypeStmt k;
        k.resolve_ast(ptr->key);
        status = k.check();
        if (!status.ok()) {
            return;
        }
        *(tptr->mutable_key()) = std::move(k.type_stmt);
    }

    void TransTypeStmt::set_tuple(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameTuple *) node;
        auto tptr = type_stmt.mutable_tuple_arg();
        if (ptr->type_args.size() < 1) {
            make_missing_required_field("types");
            return;
        }
        tptr->mutable_types()->Reserve(ptr->type_args.size());
        for (size_t i = 0; i < ptr->type_args.size(); i++) {
            TransTypeStmt k;
            k.resolve_ast(ptr->type_args[i]);
            status = k.check();
            if (!status.ok()) {
                return;
            }
            auto type_ptr = tptr->mutable_types()->Add();
            *type_ptr = std::move(k.type_stmt);
        }
    }

    void TransTypeStmt::set_union(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameUnion *) node;
        auto tptr = type_stmt.mutable_union_arg();
        if (ptr->type_args.size() < 1) {
            make_missing_required_field("types");
            return;
        }
        tptr->mutable_types()->Reserve(ptr->type_args.size());
        for (size_t i = 0; i < ptr->type_args.size(); i++) {
            auto type_ptr = tptr->mutable_types()->Add();
            status = TransNamedType::resolve_to(ptr->type_args[i], type_ptr);
            if (!status.ok()) {
                return;
            }
        }
    }

    void TransTypeStmt::set_struct(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameStruct *) node;
        auto tptr = type_stmt.mutable_struct_arg();
        if (ptr->type_args.size() < 1) {
            make_missing_required_field("types");
            return;
        }
        tptr->mutable_types()->Reserve(ptr->type_args.size());
        for (size_t i = 0; i < ptr->type_args.size(); i++) {
            auto type_ptr = tptr->mutable_types()->Add();
            status = TransNamedType::resolve_to(ptr->type_args[i], type_ptr);
            if (!status.ok()) {
                return;
            }
        }
    }

    void TransTypeStmt::set_proto(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameProto *) node;
        auto tptr = type_stmt.mutable_proto_arg();
        if (!ptr->uri) {
            make_missing_required_field("uri");
            return;
        }
        TransConstantExpr cexpr;
        cexpr.resolve_ast(ptr->uri);
        status = cexpr.check();
        if (!status.ok()) {
            return;
        }
        *tptr->mutable_uri() = std::move(cexpr.const_expr);
    }

    void TransTypeStmt::set_enum(const cantor::parser::TypeStmt *node) {
        auto ptr = (cantor::parser::TypeNameEnum *) node;
        auto tptr = type_stmt.mutable_enum_arg();
        if (ptr->type_args.size() < 1) {
            make_missing_required_field("types");
            return;
        }
        if (!ptr->uri) {
            make_missing_required_field("uri");
            return;
        }
        status = TransTypeNameUri::resolve_to(ptr->uri, tptr->mutable_uri());
        if (!status.ok()) {
            return;
        }


        tptr->mutable_element()->Reserve(ptr->type_args.size());
        for (size_t i = 0; i < ptr->type_args.size(); i++) {
            auto src = ptr->type_args[i];
            auto e = tptr->mutable_element()->Add();
            TransEnumElement en;
            en.resolve_ast(src);
            status = en.check();
            if (!status.ok()) {
                return;
            }
            *e = std::move(en.enum_element);
        }
    }

    turbo::Status TransTypeStmt::resolve_to(turbo::Nonnull<const cantor::parser::TypeStmt *> arg,
                                            turbo::Nonnull<pb::ast::TypeStmt *> out) {
        TransTypeStmt trans;
        trans.resolve_ast(arg);
        auto status = trans.check();
        if (!status.ok()) {
            return status;
        }
        *out = std::move(trans.type_stmt);
        return status;
    }
} // namespace cantor::transform
